<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .aaa {
        margin-top: 1000px;
        margin-bottom: 1000px;
      }
      .sss {
        height: 100px;
        background-color: red;
      }
    </style>
  </head>
  <body>
    <div class="aaa">
      <div class="sss">111111111111111111111111111111</div>
      <div style="width: '570px'; height: '470px';">
        <img data-src="../../图片/1.jpg" src="" alt="">
      </div>
      <div>
      </div style="width: '570px'; height: '470px';">
      <img data-src="../../图片/2.jpg" src="" alt="">
    </div>
    <script>
      const imgData = {
        img1: '../../图片/1.jpg',
        img2: '../../图片/2.jpg'
      }
      const div = document.querySelector(`.sss`)
      let imgEls = document.querySelectorAll(`img[data-src]`)
      imgEls = Array.from(imgEls)
      function inViewport(el) {
        let rect = el.getBoundingClientRect()
        return rect.top < window.innerHeight && rect.bottom > 0 
      }
      // 普通方法
      function lazyload() {
        for(let imgEl of imgEls) {
          if(inViewport(imgEl)) {
            imgEl.src = imgEl.dataset.src
            imgEl.removeEventListener('scroll', lazyload)
            // 防止滚动一直请求资源
            imgEls = imgEls.filter(i => {
              return (i !== imgEl)
            })
          }
        }
      }
      window.addEventListener('scroll', lazyload)
      const img = {
        src: '',
        loading: false,
      }
      
      const proxyImg = {}
      Object.defineProperty(proxyImg, 'src', {
        get() {
          return img.src
        },
        set(newSrc) {
          if(!img.loading && inViewport(proxyImg)) {
            img.src = newSrc
            img.loading = true
          }
        }
      })
      function setSrc() {
        for(let imgEl of imgEls) {
          proxyImg.src = imgEl.dataset.src
        }
      }

      // setSrc()
      // window.addEventListener('scroll', setSrc)
      // console.log(proxyImg.src);

      function limitRequest(promises,options) {
        let limit = options.limit || 6
        let count = 0

        function start() {
          for(let i = 0; i < limit; i++) {
            request()
          }
        } 
        function request() {
          if(count > limit || !promises.length) return
          count++
          promises.pop()().then(() => {
            request()
            count--
          })
        }
      }
    </script>
  </body>
</html>
